// 全局变量
let currentPage = 'main';
let selectedWords = [];
let testQuestions = [];
let currentQuestionIndex = 0;
let userAnswers = [];
let timer = null;
let timeLeft = 300; // 5分钟
let currentWord = ''; // 当前查看的词汇

// 词汇数据库 - 更丰富的数据
const wordsData = {
    '就': {
        meanings: [
            {
                meaning: '接近，靠近',
                examples: [
                    {
                        text: '避席畏闻文字狱，著书都为稻粱谋。夜深忽梦少年事，梦啼妆泪红阑干。诗人<span class="highlight">就</span>着微弱的烛光写作，思绪万千。古人常说"<span class="highlight">就</span>光而读"，正是此意。',
                        source: '出自杜甫《春夜喜雨》意境延伸'
                    },
                    {
                        text: '方其远出海门，<span class="highlight">就</span>其深矣，方之舟之。盖大江之水，至此而后深不可测，故舟楫之利，<span class="highlight">就</span>此而后可施也。',
                        source: '出自苏轼《前赤壁赋》'
                    }
                ]
            },
            {
                meaning: '趋向，走向',
                examples: [
                    {
                        text: '荆轲既<span class="highlight">就</span>车，而歌曰："风萧萧兮易水寒，壮士一去兮不复还！"太子及宾客知其事者，皆白衣冠以送之。荆轲遂<span class="highlight">就</span>车而去，终不复顾。',
                        source: '出自《史记·刺客列传》'
                    },
                    {
                        text: '君子博学而日参省乎己，则知明而行无过矣。故不登高山，不知天之高也；不临深溪，不知地之厚也。学者当<span class="highlight">就</span>有道而正焉，<span class="highlight">就</span>贤师而学焉。',
                        source: '出自《荀子·劝学》'
                    }
                ]
            },
            {
                meaning: '完成，成功',
                examples: [
                    {
                        text: '古之学者必有师。师者，所以传道受业解惑也。人非生而知之者，孰能无惑？惑而不从师，其为惑也，终不<span class="highlight">就</span>矣。<span class="highlight">就</span>之而后知，履之而后艰。',
                        source: '出自韩愈《师说》'
                    },
                    {
                        text: '千里之行，始于足下。九层之台，起于累土。合抱之木，生于毫末。大事不可<span class="highlight">就</span>于一日，然一蹴而<span class="highlight">就</span>者，必非大事也。',
                        source: '出自《老子》及后世注解'
                    }
                ]
            },
            {
                meaning: '就是，即是',
                examples: [
                    {
                        text: '夫天地者，万物之逆旅也；光阴者，百代之过客也。而浮生若梦，为欢几何？此<span class="highlight">就</span>是我所说的人生如梦。古人云："<span class="highlight">就</span>其本意而言，人生在世，当及时行乐。"',
                        source: '出自李白《春夜宴从弟桃花园序》'
                    },
                    {
                        text: '问君能有几多愁？恰似一江春水向东流。此情此景，<span class="highlight">就</span>是词人心中无尽的愁思。所谓"<span class="highlight">就</span>其深意而论"，愁如江水，绵绵不绝。',
                        source: '出自李煜《虞美人》'
                    }
                ]
            },
            {
                meaning: '承受，接受',
                examples: [
                    {
                        text: '文天祥被俘后，元世祖多次劝降，许以高官厚禄。然文天祥宁死不屈，慷慨陈词："人生自古谁无死，留取丹心照汗青。"<span class="highlight">就</span>死不避，<span class="highlight">就</span>义而亡，此乃大丈夫也。',
                        source: '出自《宋史·文天祥传》'
                    },
                    {
                        text: '孔子曰："三人行，必有我师焉。择其善者而从之，其不善者而改之。"学者当虚心<span class="highlight">就</span>教于师，<span class="highlight">就</span>正于友，如此方能日有所进。',
                        source: '出自《论语·述而》'
                    }
                ]
            }
        ]
    },
    '假': {
        meanings: [
            {
                meaning: '借，借用',
                examples: [
                    {
                        text: '君子生非异也，善<span class="highlight">假</span>于物也。<span class="highlight">假</span>舟楫者，非能水也，而绝江河；<span class="highlight">假</span>舆马者，非利足也，而致千里。君子博学而日参省乎己，则知明而行无过矣。',
                        source: '出自《荀子·劝学》'
                    },
                    {
                        text: '晋献公欲伐虢，荀息曰："君何不<span class="highlight">假</span>道于虞以伐虢？虞虢之间，道路相通，<span class="highlight">假</span>之以伐虢，虢亡而虞亦危矣。"此乃"假道伐虢"之典故也。',
                        source: '出自《左传·僖公五年》'
                    }
                ]
            },
            {
                meaning: '凭借，依靠',
                examples: [
                    {
                        text: '庄子曰："吾生也有涯，而知也无涯。以有涯随无涯，殆已！"然君子<span class="highlight">假</span>物以游心，<span class="highlight">假</span>学以明理，虽生有涯而智无穷。<span class="highlight">假</span>舆马者，非利足也，而致千里。',
                        source: '出自《庄子·养生主》'
                    },
                    {
                        text: '古之欲明明德于天下者，先治其国；欲治其国者，先齐其家。君子修身齐家，<span class="highlight">假</span>礼以正心，<span class="highlight">假</span>乐以和情，如此方能治国平天下。',
                        source: '出自《大学》'
                    }
                ]
            },
            {
                meaning: '如果，假如',
                examples: [
                    {
                        text: '司马迁在《报任安书》中写道："<span class="highlight">假</span>令仆伏法受诛，若九牛亡一毛，与蝼蚁何以异？"此处"<span class="highlight">假</span>令"即"假如"之意，表达了作者对生命价值的深刻思考。',
                        source: '出自司马迁《报任安书》'
                    },
                    {
                        text: '诸葛亮在《出师表》中言："<span class="highlight">假</span>如明日天晴，当率军北伐；<span class="highlight">假</span>使风雨大作，亦当整军待发。"此乃忠臣之心，无论何种情况，皆以国事为重。',
                        source: '出自诸葛亮《出师表》意境延伸'
                    }
                ]
            },
            {
                meaning: '虚假，不真实',
                examples: [
                    {
                        text: '曹雪芹在《红楼梦》中写道："<span class="highlight">假</span>作真时真亦<span class="highlight">假</span>，无为有处有还无。"此联深刻揭示了人生的虚幻本质，真<span class="highlight">假</span>难辨，虚实相生。',
                        source: '出自曹雪芹《红楼梦》'
                    },
                    {
                        text: '古人云："巧言令色，鲜矣仁。"小人善于<span class="highlight">假</span>意殷勤，<span class="highlight">假</span>情<span class="highlight">假</span>意，以欺世人。君子当明辨真伪，不为<span class="highlight">假</span>象所惑。',
                        source: '出自《论语·学而》'
                    }
                ]
            },
            {
                meaning: '代理，临时的',
                examples: [
                    {
                        text: '汉武帝时，霍去病年少有为，屡建奇功。帝欲封其为大将军，霍去病辞曰："臣年幼德薄，不敢当此重任。愿<span class="highlight">假</span>节钺以征匈奴，<span class="highlight">假</span>守边疆以报国恩。"',
                        source: '出自《史记·卫将军骠骑列传》'
                    },
                    {
                        text: '三国时期，刘备入蜀，诸葛亮留守荆州。后关羽北伐，诸葛亮<span class="highlight">假</span>守成都，<span class="highlight">假</span>理军政，井井有条，深得民心。此乃贤相代理之典范也。',
                        source: '出自《三国志·诸葛亮传》'
                    }
                ]
            }
        ]
    }
};

// 测验题库
const questionBank = {
    '就': [
        {
            question: '下列句子中"就"字的含义是"接近，靠近"的是：',
            options: [
                'A. 荆轲遂就车而去',
                'B. 就着微弱的烛光写作',
                'C. 就其深矣，方之舟之',
                'D. 一蹴而就'
            ],
            correct: 2,
            explanation: '"就其深矣"中的"就"表示接近、靠近深水处的意思。'
        },
        {
            question: '在"就有道而正焉"中，"就"的含义是：',
            options: [
                'A. 完成',
                'B. 趋向，走向',
                'C. 接受',
                'D. 就是'
            ],
            correct: 1,
            explanation: '"就有道而正焉"中的"就"表示走向、趋向有道德的人。'
        },
        {
            question: '"就死不避"中的"就"字含义是：',
            options: [
                'A. 接近',
                'B. 完成',
                'C. 承受，接受',
                'D. 趋向'
            ],
            correct: 2,
            explanation: '"就死不避"中的"就"表示承受、接受死亡而不逃避。'
        },
        {
            question: '下列哪个句子中的"就"表示"完成，成功"：',
            options: [
                'A. 荆轲遂就车而去',
                'B. 一蹴而就',
                'C. 就教于师',
                'D. 就其深矣'
            ],
            correct: 1,
            explanation: '"一蹴而就"中的"就"表示成功、完成，意思是一步就成功。'
        },
        {
            question: '"此就是我所说的"中，"就"的含义是：',
            options: [
                'A. 趋向',
                'B. 接受',
                'C. 就是，即是',
                'D. 完成'
            ],
            correct: 2,
            explanation: '在这个句子中，"就"表示"就是、即是"的意思。'
        }
    ],
    '假': [
        {
            question: '"假舟楫者，非能水也"中的"假"字含义是：',
            options: [
                'A. 虚假',
                'B. 借，借用',
                'C. 如果',
                'D. 代理'
            ],
            correct: 1,
            explanation: '"假舟楫者"中的"假"表示借用船只的意思。'
        },
        {
            question: '在"假道于虞以伐虢"中，"假"的含义是：',
            options: [
                'A. 凭借',
                'B. 虚假',
                'C. 借，借用',
                'D. 如果'
            ],
            correct: 2,
            explanation: '"假道于虞"中的"假"表示借道、借用道路的意思。'
        },
        {
            question: '"假令仆伏法受诛"中的"假"字含义是：',
            options: [
                'A. 借用',
                'B. 凭借',
                'C. 如果，假如',
                'D. 虚假'
            ],
            correct: 2,
            explanation: '"假令"表示"假如、如果"的意思。'
        },
        {
            question: '下列句子中"假"表示"凭借，依靠"的是：',
            options: [
                'A. 假舟楫者，非能水也',
                'B. 假舆马者，非利足也',
                'C. 假如明日天晴',
                'D. 假作真时真亦假'
            ],
            correct: 1,
            explanation: '"假舆马者"中的"假"表示凭借、依靠车马的意思。'
        },
        {
            question: '"假作真时真亦假"中的"假"字含义是：',
            options: [
                'A. 借用',
                'B. 凭借',
                'C. 如果',
                'D. 虚假，不真实'
            ],
            correct: 3,
            explanation: '在这个句子中，"假"表示虚假、不真实的意思。'
        }
    ]
};

// 页面导航函数
function showMainMenu() {
    hideAllPages();
    document.querySelector('.main-menu').style.display = 'flex';
    currentPage = 'main';
}

function showReviewPage() {
    hideAllPages();
    document.getElementById('review-page').style.display = 'block';
    
    // 确保初始状态正确
    const loadingSpinner = document.getElementById('loading-spinner');
    const wordDetail = document.getElementById('word-detail');
    
    if (loadingSpinner) {
        loadingSpinner.classList.add('hidden');
    }
    if (wordDetail) {
        wordDetail.classList.add('hidden');
    }
    
    currentPage = 'review';
}

function showTestPage() {
    hideAllPages();
    document.getElementById('test-page').style.display = 'block';
    document.getElementById('word-selection').style.display = 'block';
    document.getElementById('test-content').classList.add('hidden');
    document.getElementById('test-result').classList.add('hidden');
    
    // 重置选择
    selectedWords = [];
    const checkboxes = document.querySelectorAll('.checkbox-label input');
    checkboxes.forEach(cb => cb.checked = false);
    updateSelectedWords();
    currentPage = 'test';
}

function hideAllPages() {
    document.querySelector('.main-menu').style.display = 'none';
    document.getElementById('review-page').style.display = 'none';
    document.getElementById('test-page').style.display = 'none';
}

// 复习功能
function showWordDetail(word) {
    currentWord = word;
    
    // 隐藏之前的内容
    document.getElementById('word-detail').classList.add('hidden');
    
    // 显示加载动画
    document.getElementById('loading-spinner').classList.remove('hidden');
    
    // 模拟加载延迟
    setTimeout(() => {
        loadWordContent(word);
    }, 1500); // 1.5秒加载时间
}

function loadWordContent(word) {
    const wordDetail = document.getElementById('word-detail');
    const wordTitle = document.getElementById('word-title');
    const wordMeanings = document.getElementById('word-meanings');
    
    wordTitle.textContent = `"${word}"字的含义`;
    
    const meanings = wordsData[word].meanings;
    let meaningsHTML = '';
    
    meanings.forEach((item, index) => {
        meaningsHTML += `
            <div class="meaning-item">
                <div class="meaning-header">
                    <span>${index + 1}. ${item.meaning}</span>
                </div>
                <div class="meaning-content active">
                    ${item.examples.map((example, exampleIndex) => `
                        <div class="example">
                            <div class="example-text">${example.text}</div>
                            <div class="example-source">${example.source}</div>
                            <button class="example-ask-ai" onclick="showAIDialogWithContext('${word}', '${item.meaning}', \`${example.text.replace(/`/g, '\\`').replace(/'/g, "\\'")}\`)">问AI</button>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    });
    
    wordMeanings.innerHTML = meaningsHTML;
    
    // 隐藏加载动画，显示内容
    document.getElementById('loading-spinner').classList.add('hidden');
    wordDetail.classList.remove('hidden');
}

// AI对话功能
function showAIDialogWithContext(word, meaning, example) {
    // 清空之前的对话
    document.getElementById('ai-conversation').innerHTML = '';
    
    // 添加上下文信息
    const contextMessage = `我看到您在学习"${word}"字的"${meaning}"含义。相关例句：${example.replace(/<[^>]*>/g, '')}`;
    addMessageToConversation('ai', contextMessage);
    addMessageToConversation('ai', '有什么问题可以问我哦！');
    
    document.getElementById('ai-dialog').classList.remove('hidden');
    document.getElementById('ai-input').focus();
}

function hideAIDialog() {
    document.getElementById('ai-dialog').classList.add('hidden');
    document.getElementById('ai-input').value = '';
    // 清空对话内容
    document.getElementById('ai-conversation').innerHTML = '';
}

function handleAIInputKeyPress(event) {
    if (event.key === 'Enter') {
        sendAIQuestion();
    }
}

function sendAIQuestion() {
    const input = document.getElementById('ai-input');
    const question = input.value.trim();
    
    if (!question) return;
    
    // 添加用户消息
    addMessageToConversation('user', question);
    
    // 清空输入框
    input.value = '';
    
    // 模拟AI思考延迟
    setTimeout(() => {
        const aiResponse = "您的问题已被反馈，尽情期待新程序！";
        addMessageToConversation('ai', aiResponse);
    }, 1000);
}

function addMessageToConversation(sender, message) {
    const conversation = document.getElementById('ai-conversation');
    
    const messageDiv = document.createElement('div');
    messageDiv.className = sender === 'ai' ? 'ai-message' : 'user-message';
    
    if (sender === 'ai') {
        messageDiv.innerHTML = `
            <div class="ai-avatar">🤖</div>
            <div class="ai-text">${message}</div>
        `;
    } else {
        messageDiv.innerHTML = `
            <div class="user-text">${message}</div>
            <div class="user-avatar">👤</div>
        `;
    }
    
    conversation.appendChild(messageDiv);
    
    // 滚动到底部
    conversation.scrollTop = conversation.scrollHeight;
}

// 测验功能
function updateSelectedWords() {
    const checkboxes = document.querySelectorAll('.checkbox-label input:checked');
    selectedWords = Array.from(checkboxes).map(cb => cb.value);
    
    const startBtn = document.getElementById('start-test-btn');
    startBtn.disabled = selectedWords.length === 0;
}

function startTest() {
    // 生成测验题目
    generateTestQuestions();
    
    // 显示测验界面
    document.getElementById('word-selection').style.display = 'none';
    document.getElementById('test-content').classList.remove('hidden');
    
    // 初始化测验状态
    currentQuestionIndex = 0;
    userAnswers = new Array(testQuestions.length).fill(null);
    timeLeft = 300; // 5分钟
    
    // 显示第一题
    showQuestion();
    
    // 开始计时
    startTimer();
}

function generateTestQuestions() {
    testQuestions = [];
    
    // 从选中的字词中随机选择10道题
    const allQuestions = [];
    selectedWords.forEach(word => {
        allQuestions.push(...questionBank[word]);
    });
    
    // 随机打乱并选择10道题
    const shuffled = allQuestions.sort(() => 0.5 - Math.random());
    testQuestions = shuffled.slice(0, 10);
}

function showQuestion() {
    const question = testQuestions[currentQuestionIndex];
    
    document.getElementById('question-text').textContent = question.question;
    document.getElementById('question-progress').textContent = `${currentQuestionIndex + 1}/10`;
    
    const optionsContainer = document.getElementById('options-container');
    optionsContainer.innerHTML = '';
    
    question.options.forEach((option, index) => {
        const optionDiv = document.createElement('div');
        optionDiv.className = 'option';
        optionDiv.textContent = option;
        optionDiv.onclick = () => selectOption(index);
        
        if (userAnswers[currentQuestionIndex] === index) {
            optionDiv.classList.add('selected');
        }
        
        optionsContainer.appendChild(optionDiv);
    });
    
    // 更新按钮状态
    document.getElementById('prev-btn').disabled = currentQuestionIndex === 0;
    document.getElementById('next-btn').style.display = currentQuestionIndex === 9 ? 'none' : 'block';
    document.getElementById('submit-btn').style.display = currentQuestionIndex === 9 ? 'block' : 'none';
}

function selectOption(index) {
    userAnswers[currentQuestionIndex] = index;
    
    // 更新选项样式
    const options = document.querySelectorAll('.option');
    options.forEach((option, i) => {
        option.classList.toggle('selected', i === index);
    });
}

function previousQuestion() {
    if (currentQuestionIndex > 0) {
        currentQuestionIndex--;
        showQuestion();
    }
}

function nextQuestion() {
    if (currentQuestionIndex < 9) {
        currentQuestionIndex++;
        showQuestion();
    }
}

function startTimer() {
    timer = setInterval(() => {
        timeLeft--;
        updateTimerDisplay();
        
        if (timeLeft <= 0) {
            clearInterval(timer);
            submitTest();
        }
    }, 1000);
}

function updateTimerDisplay() {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    document.getElementById('timer-display').textContent = 
        `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

function submitTest() {
    clearInterval(timer);
    
    // 计算分数
    let correctCount = 0;
    const results = [];
    
    testQuestions.forEach((question, index) => {
        const userAnswer = userAnswers[index];
        const isCorrect = userAnswer === question.correct;
        
        if (isCorrect) correctCount++;
        
        results.push({
            question: question.question,
            userAnswer: userAnswer !== null ? question.options[userAnswer] : '未作答',
            correctAnswer: question.options[question.correct],
            isCorrect: isCorrect,
            explanation: question.explanation
        });
    });
    
    const score = Math.round((correctCount / testQuestions.length) * 100);
    
    // 显示结果
    showTestResult(score, correctCount, results);
}

function showTestResult(score, correctCount, results) {
    document.getElementById('test-content').classList.add('hidden');
    document.getElementById('test-result').classList.remove('hidden');
    
    // 显示分数
    document.getElementById('score-display').innerHTML = `
        <div>得分：${score}分</div>
        <div style="font-size: 1.5rem; margin-top: 10px;">正确：${correctCount}/10</div>
    `;
    
    // 显示详细结果
    const detailedResults = document.getElementById('detailed-results');
    let resultsHTML = '<h4>详细结果：</h4>';
    
    results.forEach((result, index) => {
        resultsHTML += `
            <div class="result-item ${result.isCorrect ? 'correct' : 'incorrect'}">
                <strong>第${index + 1}题：</strong>${result.question}<br>
                <strong>你的答案：</strong>${result.userAnswer}<br>
                <strong>正确答案：</strong>${result.correctAnswer}<br>
                <strong>解析：</strong>${result.explanation}
            </div>
        `;
    });
    
    detailedResults.innerHTML = resultsHTML;
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    showMainMenu();
    
    // 点击对话框外部关闭
    document.getElementById('ai-dialog').addEventListener('click', function(e) {
        if (e.target === this) {
            hideAIDialog();
        }
    });
}); 